package com.kt.common.coroutines

import kotlinx.coroutines.*



/*fun main() = runBlocking<Unit> {
    Thread(Runnable {

        launch { // 运行在父协程的上下文中，即 runBlocking 主协程
            println("main runBlocking      : I'm working in thread ${Thread.currentThread().name}")
        }
    }, "aaaa").start()


    launch(Dispatchers.Unconfined) { // 不受限的——将工作在主线程中
        println("Unconfined            : I'm working in thread ${Thread.currentThread().name}")
    }

    launch(Dispatchers.Default) { // // 将会获取默认调度器
        println("Default               : I'm working in thread ${Thread.currentThread().name}")
    }

    launch(newSingleThreadContext("myNewThread")) {// 将使它获得一个新的线程
        println("newSingleThreadContext: I'm working in thread ${Thread.currentThread().name}")
    }

    //Unconfined            : I'm working in thread main
    //Default               : I'm working in thread DefaultDispatcher-worker-1
    //newSingleThreadContext: I'm working in thread myNewThread
    //main runBlocking      : I'm working in thread main
}*/


/*
fun main() = runBlocking<Unit> {
    launch(Dispatchers.Unconfined) { // 非受限的——将和主线程一起工作
        println("Unconfined      : I'm working in thread ${Thread.currentThread().name}")
        delay(500)
        println("Unconfined      : After delay in thread ${Thread.currentThread().name}")
    }
    launch { // 父协程的上下文，主 runBlocking 协程
        println("main runBlocking: I'm working in thread ${Thread.currentThread().name}")
        delay(1000)
        println("main runBlocking: After delay in thread ${Thread.currentThread().name}")
    }
}*/

fun log(msg: String) = println("[${Thread.currentThread().name}] $msg")

/*
fun main() = runBlocking<Unit> {
    val a = async {
        log("I'm computing a piece of the answer")
        6
    }
    val b = async {
        log("I'm computing another piece of the answer")
        7
    }
    log("The answer is ${a.await() * b.await()}")
}*/


/*
fun main() {
    newSingleThreadContext("ctx1").use {
        ctx1->
        newSingleThreadContext("ctx2").use {
            runBlocking(ctx1){
                log("Started in ctx1${Thread.currentThread()}")
                withContext(it){
                    log("Working in ctx2${Thread.currentThread()}")
                }
                log("Back to ctx1${Thread.currentThread()}")
            }
        }
    }

}*/

/*
fun main() = runBlocking<Unit> {
    println("My job is ${coroutineContext[Job]} ${coroutineContext[Job]?.isActive == true}")
}*/

/*
fun main() = runBlocking<Unit> {
    val request = launch {
        // 孵化了两个子作业, 其中一个通过 GlobalScope 启动
        GlobalScope.launch {
            println("job1: I run in GlobalScope and execute independently!")
            delay(1000)
            println("job1: I am not affected by cancellation of the request")
        }
        // 另一个则承袭了父协程的上下文
        launch {
            delay(100)
            println("job2: I am a child of the request coroutine")
            delay(1000)
            println("job2: I will not execute this line if my parent request is cancelled")
        }
    }

    delay(500)
    request.cancel() // 取消请求（request）的执行
    delay(1000) // 延迟一秒钟来看看发生了什么
    println("main: Who has survived request cancellation?")

}*/

/*
fun main() = runBlocking<Unit> {
    // 启动一个协程来处理某种传入请求（request）
    val request = launch {
        repeat(3) { i -> // 启动少量的子作业
            launch  {
                delay((i + 1) * 1000L) // 延迟 200 毫秒、400 毫秒、600 毫秒的时间
                println("Coroutine $i is done")
            }
        }
        println("request: I'm done and I don't explicitly join my children that are still active")
    }
    request.join() // 等待请求的完成，包括其所有子协程
    println("Now processing of the request is complete")
}*/



/*fun main() = runBlocking(CoroutineName("main")) {
    log("Started main coroutine")
    // 运行两个后台值计算
    val v1 = async(CoroutineName("v1coroutine")) {
        delay(500)
        log("Computing v1")
        252
    }
    val v2 = async(CoroutineName("v2coroutine")) {
        delay(1000)
        log("Computing v2")
        6
    }
    log("The answer for v1 / v2 = ${v1.await() / v2.await()}")
}*/

/*
fun main()= runBlocking<Unit> {
    val mainScope = CoroutineScope(NonCancellable)
    repeat(10){
        mainScope.launch {
            delay(it * 500L)
            println("this coroutine")
        }
    }


    delay(3000)

    mainScope.cancel()
}*/


//线程局部数据
val threadLocal = ThreadLocal<String?>() // 声明线程局部变量

fun main() = runBlocking<Unit> {
    threadLocal.set("main")
    println("Pre-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
    val job = launch(Dispatchers.Default + threadLocal.asContextElement(value = "launch")) {
        println("Launch start, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
        yield()
        println("After yield, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")
    }
    job.join()
    println("Post-main, current thread: ${Thread.currentThread()}, thread local value: '${threadLocal.get()}'")


}